import * as cloudDb from '@agconnect/database-server';
import { resource } from './model/resource';
import { topic } from './model/topic';
import { user_history } from './model/user_history';
import { topic_resource } from './model/topic_resource';
import { collect } from './model/collect';
import { user_like } from './model/user_like';
import { ResourceResp } from './model/ResourceResp';
import * as agc from '@agconnect/common-server';
import * as Utils from './utils/Utils.js';

const ZONE_NAME = "HarmonyOSDeveloper";

export class DatabaseHelper {
  logger;
  cloudDbZone;

  constructor(context, logger) {
    this.logger = logger;
    const credential = Utils.getCredential(context, logger);
    try {
      // 初始化AGCClient
      logger.info("begin to init agcClient");
      let agcClient;
      try {
        agcClient = agc.AGCClient.getInstance();
      } catch {
        agc.AGCClient.initialize(credential);
        agcClient = agc.AGCClient.getInstance();
      }
      // 初始化AGConnectCloudDB实例
      logger.info("begin to init cloudDb");
      let cloudDbInstance;
      try {
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      } catch {
        cloudDb.AGConnectCloudDB.initialize(agcClient);
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      }
      // 创建CloudDBZoneConfig配置对象，并设置云侧CloudDB zone名称，打开Cloud DB zone实例
      const cloudDBZoneConfig = new cloudDb.CloudDBZoneConfig(ZONE_NAME);
      this.cloudDbZone = cloudDbInstance.openCloudDBZone(cloudDBZoneConfig);
    } catch (err) {
      logger.error("init CloudDBZoneWrapper error: " + err);
    }
  }

  async queryResource(userid) {
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      // 查询历史记录表
      let resList = [];
      let historyIds = [];
      const historyQuery = cloudDb.CloudDBZoneQuery.where(user_history).orderByDesc("browse_time");
      historyQuery.equalTo('user_id', userid);
      const historyResp = await this.cloudDbZone.executeQuery(historyQuery);
      let historyData = historyResp.getSnapshotObjects();
      console.log('resp historyData=>', historyData);
      if (historyData.length <= 0) {
        return undefined;
      }
      for (let i = 0; i < historyData.length; i++) {
        let historyItem: user_history = historyData[i];
        historyIds.push(historyItem.getResource_id())
      }
      const resourceQuery = cloudDb.CloudDBZoneQuery.where(resource);
      resourceQuery.in("id", historyIds);
      const resourceResp = await this.cloudDbZone.executeQuery(resourceQuery);
      let resourceData = resourceResp.getSnapshotObjects();
      this.logger.info("query resource success ");
      console.log('resp=>', resourceData);

      let likedIds = await this.queryLikedIds(userid);
      let collectedIds = await this.queryCollectedIds(userid);

      if (resourceData.length <= 0) {
        return undefined;
      }

      resourceData.sort(function (a, b) {
        return historyIds.indexOf(a.getId()) - historyIds.indexOf(b.getId()); //	降序，升序则反之
      });
      let topics: topic[] = await this.queryTopic();
      for (let i = 0; i < resourceData.length; i++) {
        let dataQ = resourceData[i];
        resList.push(new ResourceResp(
          dataQ.getId(),
          dataQ.getTitle(),
          dataQ.getBrief(),
          dataQ.getHeader_src(),
          dataQ.getType(),
          dataQ.getWeb_url(),
          dataQ.getPublish_date(),
          this.getTopicNames(topics, dataQ.getTopics()),
          dataQ.getViews_count(),
          dataQ.getCollect_count(),
          dataQ.getLikes_count(),
          dataQ.getTag(),
          dataQ.getBanner_src(),
          dataQ.getMedia_src(),
          likedIds.indexOf(dataQ.getId()) !== -1, // isLiked
          collectedIds.indexOf(dataQ.getId()) !== -1, // isCollected
          false
        ))
      }
      return resList;
    } catch (error) {
      this.logger.info("query resource error " + error);
      return undefined;
    }
  }

  async queryLikedIds(userid) {
    let likedIds = [];
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      const likeQuery = cloudDb.CloudDBZoneQuery.where(user_like);
      likeQuery.equalTo('user_id', userid);
      const likeResp = await this.cloudDbZone.executeQuery(likeQuery);
      let likeData = likeResp.getSnapshotObjects();
      this.logger.info("query like resource success ");
      console.log('resp like=>', likeResp);
      for (let index = 0; index < likeData.length; index++) {
        const element: user_like = likeData[index];
        likedIds.push(element.getResource_id());
      }
      return likedIds;
    } catch (error) {
      this.logger.info("query resource error " + error);
    }
  }

  async queryCollectedIds(userid) {
    let collectedIds = [];
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      const collectedQuery = cloudDb.CloudDBZoneQuery.where(collect);
      collectedQuery.equalTo('user_id', userid);
      const collectedResp = await this.cloudDbZone.executeQuery(collectedQuery);
      let collectedData = collectedResp.getSnapshotObjects();
      this.logger.info("query collected resource success ");
      console.log('resp collected=>', collectedResp);
      for (let index = 0; index < collectedData.length; index++) {
        const element: collect = collectedData[index];
        collectedIds.push(element.getResource_id());
      }
      return collectedIds;
    } catch (error) {
      this.logger.info("query resource error " + error);
    }
  }

  async queryTopic() {
    // 查询所有主题
    const cloudDBZoneQuery = cloudDb.CloudDBZoneQuery.where(topic);
    const resp = await this.cloudDbZone.executeQuery(cloudDBZoneQuery);
    let listData = resp.getSnapshotObjects();
    this.logger.info("query topic success ");
    console.log('queryTopic listData=>', listData.length);
    return listData;
  }

  getTopicNames(topics: topic[], tidStr: string) {
    let topicNames = []
    let topicIds: string[] = tidStr.split(',');
    for (let index = 0; index < topicIds.length; index++) {
      const tid = topicIds[index];
      let tp:topic[] = topics.filter(tp => tp.getId() === tid);
      topicNames.push(tp[0].getName())
    }
    return topicNames;
  }

  async queryFollowedTopicResourceIds(topicIds) {
    let resourceIds = [];
    try {
      const topicResourceQuery = cloudDb.CloudDBZoneQuery.where(topic_resource);
      topicResourceQuery.in('topic_id', topicIds);
      const topicResourceResp = await this.cloudDbZone.executeQuery(topicResourceQuery);
      let topicResourceRespData = topicResourceResp.getSnapshotObjects();
      this.logger.info("query topicResourceRespData success ");
      console.log('resp topicResourceRespData=>', topicResourceRespData.length);
      for (let index = 0; index < topicResourceRespData.length; index++) {
        const element: topic_resource = topicResourceRespData[index];
        if (!resourceIds.includes(element.getResource_id())) {
          resourceIds.push(element.getResource_id());
        }
      }
    } catch (error) {
      this.logger.info("query resource error " + error);
    } finally {
      return resourceIds;
    }
  }
}